package net1;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class UdpEchoClient {
    private static final SocketAddress address = new InetSocketAddress("127.0.0.1", 8888);

    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket();
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("--------------------------------");
            System.out.println("请输入要展示的目录");
            String request = scanner.next() + "\3";
            byte[] requestData = request.getBytes(StandardCharsets.UTF_8);
            DatagramPacket requestPacket = new DatagramPacket(requestData, requestData.length, address);
            socket.send(requestPacket);

            byte[] responseData = new byte[1024];
            DatagramPacket responsePacket = new DatagramPacket(responseData, responseData.length);
            socket.receive(responsePacket);
            System.out.println("该目录下的文件列表为：");

            int next = 0;
            for (int i = 0; i < responseData.length; i++) {
                byte b = responseData[i];
                if (b == '\3') {
                    break;
                }
                if (b == '\n') {
                    String fileName = new String(responseData, next, i - next);
                    System.out.println(fileName);
                    next = i + 1;
                }
            }
        }
    }
}
